import { onMounted, reactive, ref } from 'vue';
import { useRoute } from "vue-router";
import _ from "lodash";
import * as BaseDataUtils from '../utils/useBaseData';
import * as TypeUtils from "../utils/useType";
import * as CompUtils from "../utils/useComp";
import * as ToolUtils from "../utils/useTool";
import * as ConfigUtils from "../utils/useConfig";
import * as Api from '@/api/configCenter/configCenter';
import type { TableColumnData } from "@arco-design/web-vue";
import type * as ApiType from "@/api/configCenter/configCenter.d";
import type { CallBackData } from '@/components/dialog/type.d';
import {checkPermission} from '@/directive/role/index';
import { getPermCode } from "../utils/useBaseData";


const usePageData = () => {
  const route = useRoute();
  let dataInfo = reactive({
    searchPlaceholder: "",
    pageTitle: "",
    currentLabelCode:'',
    isLeftContainer: false,
    columns: [] as TableColumnData[],
    data: [] as any,
    total: 0,
    stickyHeader: true,
    showPageSize: true,
    scrollbar: true,
    scroll: {
      x: '100%',
      y: '100%'
    },
    searchForm: {
      page: 1,
      pageSize: 10
    } as ApiType.GetLesionParams,
    pageType: 0,
    pageField: 'name',
    labelModel: {
      parentId: 0,
      page: 1,
      pageSize: 10
    } as ApiType.GetLabelDataParams,
    listData: [] as ApiType.LabelListItem[],
    paginationProps: {
      defaultPageSize: 10,
      total: 0,
    },
    field: 'name',
    placeholder: '',
    loading: false
  });
  if (route) {
    dataInfo = reactive({
      ...dataInfo,
      ...BaseDataUtils.getBaseData(route.path)
    })
  }
  let dialogDataInfo = reactive({
    visible: false,
    viewMode: BaseDataUtils.viewMode.CREATE,
    title: "提示",
    width: 0,
    isForm: false,
    maskClosable: false,
    okText: "确认",
    modalClass: "model",
    footer: true,
    hideCancel: false,
    isParent: true,
    modelForm: {} as any, 
    rules: {},
    parentName: "",
    okButtonProps: {
      disabled: false
    }
  })
  const formRef = ref();

  /**
   * 根据路由页面类型初始化获取表格数据
   */
  const initData = async () => {
    if (dataInfo.pageType !== 4) {
      const params = {
        ...dataInfo.searchForm,
      }
      const res = await BaseDataUtils.getTableData(dataInfo.pageType, params);
      res && (dataInfo.total = res.total);
      res && (dataInfo.data = res.list);
    }
    if (dataInfo.pageType === 4) {
      const params = {
        // configList: []
        ...dataInfo.searchForm,
        parentId: 0
      }
      const res = await Api.getLabelData(params);
      res.list && (dataInfo.listData = res.list.filter(it =>
          checkPermission(getPermCode(dataInfo.pageType, it.code))
      ));// 数据级别的权限判断,比用v-role命令彻底
      dataInfo.paginationProps.total = res.total;
    }
  }

  /**
   * 查询表格查询组件事件
   */
  const search = () => {
    initData();
  }

  /**
   * 重置表格查询组件事件
   */
  const reset = () => {
    dataInfo.searchForm = {
      page: 1,
      pageSize: 10
    }
    initData();
  }

  /**
   * 配置中心除标签配置外的列表分页方法
   * @param size 当前页码
   */
  const handleSizeChange = (size: number) => {
    dataInfo.searchForm = {
      ...dataInfo.searchForm,
      page: size
    };
    initData();
  }

  /**
   * 配置中心除标签配置外的列表分页方法
   * @param pageSize 当前条数
   */
  const handleCurrentSizeChange = (pageSize: number) => {
    dataInfo.searchForm = {
      ...dataInfo.searchForm,
      pageSize
    };
    initData();
  }

  /**
   * 配置中心除标签配置外的列表新增方法
   */
  const handleAddClick = () => {
    const { baseData, modelForm } = BaseDataUtils.getModelBase(dataInfo.pageType, BaseDataUtils.viewMode.CREATE);
    dialogDataInfo.title = baseData.title;
    dialogDataInfo.viewMode = baseData.viewMode;
    dialogDataInfo.width = baseData.width;
    dialogDataInfo.isForm = baseData.isForm;
    dialogDataInfo.maskClosable = baseData.maskClosable;
    dialogDataInfo.modelForm = modelForm;
    if (dialogDataInfo.modelForm.groupFlag === false) {
      getMaxCode(!dialogDataInfo.modelForm.groupFlag);
    }
    dialogDataInfo.rules = {
      name: [{ required: true, message: '名称不能为空！', trigger: 'blur, change'}],
    }
    dialogDataInfo.visible = baseData.visible;
  }

  /**
   * 配置中心除标签配置外的列表编辑方法
   * @param item 当前点击的一项
   */
  const handleUpdateClick = (item: any) => {
    const { baseData, modelForm } = BaseDataUtils.getModelBase(dataInfo.pageType, BaseDataUtils.viewMode.EDIT, item);
    dialogDataInfo.visible = baseData.visible;
    dialogDataInfo.viewMode = baseData.viewMode;
    dialogDataInfo.title = baseData.title;
    dialogDataInfo.width = baseData.width;
    dialogDataInfo.isForm = baseData.isForm;
    dialogDataInfo.maskClosable = baseData.maskClosable;
    dialogDataInfo.modelForm = modelForm;
    if (dataInfo.pageType === 2 && item.type !== "text" && typeof item.data === "string") {
      item.parameter = JSON.parse(item.parameter);
      item.data = JSON.parse(item.data);
    }
    dialogDataInfo.modelForm = _.cloneDeep(item);
    dialogDataInfo.rules = {
      name: [{ required: true, message: '名称不能为空！', trigger: 'blur, change'}],
      // value: [{ required: true, message: '不能为空！', trigger: 'blur, change'}],
    }
  }
  /**
   * 配置中心-标注组件的列表查看方法
   */
  const handleViewClick = (item: any) => {
    const { baseData, modelForm } = BaseDataUtils.getModelBase(dataInfo.pageType, BaseDataUtils.viewMode.VIEW);
    dialogDataInfo.visible = baseData.visible;
    dialogDataInfo.viewMode = baseData.viewMode;
    dialogDataInfo.title = baseData.title;
    dialogDataInfo.width = baseData.width;
    dialogDataInfo.isForm = baseData.isForm;
    dialogDataInfo.maskClosable = baseData.maskClosable;
    dialogDataInfo.modelForm = modelForm;
    if (dataInfo.pageType === 2 && item.type !== "text" && typeof item.data === "string") {
      item.parameter = JSON.parse(item.parameter);
      item.data = JSON.parse(item.data);
    }
    dialogDataInfo.modelForm = _.cloneDeep(item);
    dialogDataInfo.rules = {
      name: [{ required: true, message: '名称不能为空！', trigger: 'blur, change'}],
    }
  }
  /**
   * 标签类型弹窗获取最大code值方法
   * @param type 当前病灶类型
   */
  const getMaxCode = async (type: boolean) => {
    const res = await Api.getLesionMaxCode();
    if (type) {
      const num = +res.data.maxCode.split('ANNO')[1] + 1;
      dialogDataInfo.modelForm.value = "ANNO" + num;
    }
  }

  /**
   * 标签类型弹窗的种类值切换方法
   * @param flag 标签类型弹窗的种类值 true 病灶群组 false 单一病灶
   */
  const handleGroupChange = (flag: boolean) => {
    if (flag) {
      dialogDataInfo.modelForm.childs[0].value = dialogDataInfo.modelForm.value + "_1";
    }
  }

  /**
   * 配置中心除标注配置之外的增加icon的方法
   * @param index 当前索引+1
   */
  const handleCompAdd = (index: number) => {
    if (dialogDataInfo.modelForm.type !== "text") {
      if (dialogDataInfo.modelForm.type === "child_select") {
        dialogDataInfo.modelForm.data.push({
          text: undefined,
          code: undefined,
          child: [
            {
              text: undefined,
              code: undefined,
              child: undefined
            }
          ]
        });
        changeCompCode();
        // changeChildCompCode(index - 1);
      } else {
        dialogDataInfo.modelForm.data.push({
          text: undefined,
          code: undefined,
        });
        changeCompCode();
      }
    }
  }

  /**
   * 配置中心除标注配置之外的删除icon的方法
   * @param index 当前索引
   */
  const handleCompDel = (index: number) => {
    // && dialogDataInfo.modelForm.type !== "child_select"
    if (dialogDataInfo.modelForm.type !== "text") {
      dialogDataInfo.modelForm.data.splice(index, 1);
      changeCompCode();
      // dialogDataInfo.modelForm.type === "child_select" && changeChildCompCode();
    }
  }

  /**
   * 针对增加的数据集合处理code编码值
   */
  const changeCompCode = () => {
    dialogDataInfo.modelForm.data = dialogDataInfo.modelForm.data.map((item: { code: any; child: null | any[] }, index: number) => {
      let newIndex = index + 1;
      item.code = newIndex;
      if (item.child) {
        item.child = item.child.map((t, i) => {
          let newI = i + 1;
          t.code = newI;
          return t;
        })
      }
      return item;
    })
  }

  const changeChildCompCode = (parentIndex: number) => {
    dialogDataInfo.modelForm.data[parentIndex].child = dialogDataInfo.modelForm.data[parentIndex].child.map((item: { code: number; }, index: number) => {
      let i = index + 1;
      item.code = i;
      return item;
    })
  }

  const handleCompChildAdd = (parentIndex: number, index: number) => {
    dialogDataInfo.modelForm.data[parentIndex].child.push({
      text: undefined,
      code: undefined,
      child: undefined
    });
    changeChildCompCode(parentIndex);
  }

  const handleCompChildDel = (parentIndex: number, index: number) => {
    dialogDataInfo.modelForm.data[parentIndex].child.splice(index, 1);
    changeChildCompCode(parentIndex);
  }

  const handleCancel = () => {
    console.log('关闭1');
  }

  /**
   * 弹窗点击右上角，取消，确定操作
   */
  const handleVisible = async (modalData: CallBackData) => {
    let flag: string = BaseDataUtils.viewMode.CREATE;
    if (modalData.status === "clear") {
      dialogDataInfo.visible = modalData.flag;
      if (dataInfo.pageType === 3 || dataInfo.pageType === 4) {
        formRef.value.resetFields();
      }
      return;
    }
    flag = dialogDataInfo.viewMode;

    formRef.value.validate(async (validate: any) => {
      if (!validate) {
        if (dataInfo.pageType === 1) {
          const returnFlag = await TypeUtils.saveInterface(dialogDataInfo, modalData, flag);
          returnFlag && initData();
        }else if(dataInfo.pageType === 2){
          const returnFlag = await CompUtils.saveInterface(dialogDataInfo, modalData, flag);
          returnFlag && initData();
        }else if(dataInfo.pageType === 3){
          const returnFlag = await ToolUtils.saveInterface(dialogDataInfo, modalData);
          returnFlag && initData();
        }else if(dataInfo.pageType === 4){
          const returnFlag = await ConfigUtils.saveInterface(dialogDataInfo, modalData, flag);
          returnFlag && dialogDataInfo.isParent && initData();
          returnFlag && !dialogDataInfo.isParent && getLabelChildList();
        }
      }
      modalData.done && modalData.done(true)//处理弹框确认按钮ok-loading为false
    })
  }

  /**
   * 标签配置页面的左侧标签点击事件
   * @param id 当前点击的id
   */
  const handleLabelClick = (item: ApiType.LabelListItem) => {
    dataInfo.pageType = 4;
    dataInfo.currentLabelCode = item.code
    dataInfo.columns = BaseDataUtils.getLabelItemColumns(item.id);
    const { labelModel, result } = BaseDataUtils.getLabelItemBase(item);
    dataInfo.labelModel.parentId = labelModel.parentId;
    dataInfo.pageTitle = result.pageTitle;
    dataInfo.field = result.field;
    dataInfo.pageField = result.pageField;
    dataInfo.searchPlaceholder = result.searchPlaceholder;
    dialogDataInfo.isParent = false;
    dialogDataInfo.modelForm.parentCode = item.code;
    dialogDataInfo.modelForm.parentId = item.id;
    dialogDataInfo.modelForm.parentName = item.name;
    dialogDataInfo.parentName = item.name;
    getLabelChildList();
  }

  /**
   * 标签配置的子项列表查询时间
   */
  const getLabelChildList = async () => {
    dataInfo.loading = true;
    const params = {
      // configList: []
      ...dataInfo.labelModel
    }
    const res = await Api.getLabelData(params);
    res && (dataInfo.total = res.total);
    res && (dataInfo.data = res.list);
    dataInfo.loading = false;
  }

  /**
   * 标签配置的查询方法
   */
  const handleSearch = () => {
    dataInfo.searchForm.name === "" && (dataInfo.searchForm.name = undefined);
    // dataInfo.labelModel.parentId = 0;
    initData();
  }

  /**
   * 标签配置的分页方法
   * @param page 标签配置的页码
   */
  const handlePageChange = (page: number) => {
    console.log(page, "asdadsasd");
  }

  /**
   * 标签配置的子项列表分页方法
   * @param size 当前页码
   */
  const handleChildSizeChange = (size: number) => {
    dataInfo.labelModel = {
      ...dataInfo.labelModel,
      page: size
    };
    getLabelChildList();
  }

  /**
   * 标签配置的子项列表分页方法
   * @param pageSize 当前条数
   */
  const handleChildCurrentSizeChange = (pageSize: number) => {
    dataInfo.labelModel = {
      ...dataInfo.labelModel,
      pageSize
    };
    getLabelChildList();
  }

  /**
   * 标签配置的编辑方法
   * @param item 当前标签配置的一项
   */
  const handleLabelEdit = (item: ApiType.LabelListItem) => {
    const { baseData, modelForm } = BaseDataUtils.getModelBase(dataInfo.pageType, BaseDataUtils.viewMode.EDIT, item);
    dialogDataInfo.visible = baseData.visible;
    // dialogDataInfo.title = baseData.title;
    dialogDataInfo.width = baseData.width;
    dialogDataInfo.isForm = baseData.isForm;
    dialogDataInfo.maskClosable = baseData.maskClosable;
    dialogDataInfo.isParent = baseData.isParent;
    dialogDataInfo.modelForm = modelForm;
    dialogDataInfo.modelForm = _.cloneDeep(item);
    // dialogDataInfo.modelForm.parentCode = item.code;
    dialogDataInfo.modelForm.parentId = dataInfo.labelModel.parentId;
    // dialogDataInfo.modelForm.parentName = item.name;
    dialogDataInfo.title = "编辑" + item.name;
  }

  /**
   * 标签配置的子项查询方法
   */
  const handleChildSearch = () => {
    dataInfo.labelModel.name === "" && (dataInfo.labelModel.name = undefined);
    getLabelChildList();
  }

  /**
   * 标签配置的子项新增方法
   */
  const handleChildAdd = async () => {
    let parentId = dialogDataInfo.modelForm.parentId;
    let parentName = dialogDataInfo.parentName;
    let parentCode = dialogDataInfo.modelForm.parentCode;
    dialogDataInfo.title = "新建" + parentName;
    dialogDataInfo.modelForm.name = null;
    dialogDataInfo.modelForm.value = null;
    dialogDataInfo.modelForm.code = null;
    dialogDataInfo.viewMode = BaseDataUtils.viewMode.CREATE;
    const params = {
      codePrefix: parentCode
    };
    dialogDataInfo.rules = {
      name: [{ required: true, message: '名称不能为空！', trigger: 'blur, change'}],
      // value: [{ required: true, message: '不能为空！', trigger: 'blur, change'}],
    }
    // code码接口有异常
    const res = await Api.getLabelMaxCode(params);
    if (res.code === 200) {
      if (res.data) {
        const num = +res.data.substr(1, res.data.length) + 1;
        let resStr = "";
        num < 10 && (resStr = `${res.data.substring(0, 1)}00${num}`);
        (num < 100 && num >= 10) && (resStr = `${res.data.substring(0, 1)}0${num}`);
        num > 100 && (resStr = res.data.substring(0, 1) + num);
        dialogDataInfo.modelForm.code = resStr;
      }
      if (!res.data) {
        dialogDataInfo.modelForm.code = `${params.codePrefix}001`;
      }
      dialogDataInfo.visible = true;
    }
  }

  /**
   * 标签配置的子项编辑方法
   * @param item 当前点击的子项的其中一项
   */
  const handleChildUpdate = (item: ApiType.LabelListItem) => {
    let parentId = dialogDataInfo.modelForm.parentId;
    let parentName = dialogDataInfo.parentName;
    let parentCode = dialogDataInfo.modelForm.parentCode;
    dialogDataInfo.modelForm = _.cloneDeep(item);
    dialogDataInfo.modelForm.parentId = parentId;
    dialogDataInfo.modelForm.parentCode = parentCode;
    dialogDataInfo.title = "编辑" + parentName;
    dialogDataInfo.viewMode = BaseDataUtils.viewMode.EDIT;
    dialogDataInfo.rules = {
      name: [{ required: true, message: '名称不能为空！', trigger: 'blur, change'}],
      // value: [{ required: true, message: '不能为空！', trigger: 'blur, change'}],
    }
    dialogDataInfo.visible = true;
  }

  // 标注类型弹窗子项增加事件
  const handleTypeAdd = (index: number) => {
    dialogDataInfo.modelForm.childs.push({
      name: undefined,
      value: `${dialogDataInfo.modelForm.value}_${dialogDataInfo.modelForm.childs.length + 1}`,
    });
  }

  // 标注类型弹窗子项删除事件
  const handleTypeDel = (index: number) => {
    dialogDataInfo.modelForm.childs.splice(index, 1);
    dialogDataInfo.modelForm.childs = dialogDataInfo.modelForm.childs.map((item: { value: string; }, index: number) => {
      item.value = `${dialogDataInfo.modelForm.value}_${index + 1}`;
      return item;
    })
  }

  onMounted(() => (initData()))

  return {
    dataInfo,
    dialogDataInfo,
    formRef,
    search,
    reset,
    handleLabelClick,
    handleSearch,
    handlePageChange,
    handleChildSearch,
    handleLabelEdit,
    handleSizeChange,
    handleCurrentSizeChange,
    handleAddClick,
    handleUpdateClick,
    handleViewClick,
    handleChildAdd,
    handleChildUpdate,
    handleCancel,
    handleVisible,
    handleTypeAdd,
    handleTypeDel,
    handleGroupChange,
    handleCompAdd,
    handleCompDel,
    handleCompChildDel,
    handleCompChildAdd,
    handleChildSizeChange,
    handleChildCurrentSizeChange
  }
};

export default usePageData;